<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算属性</title>
    <script src="../vue.js"></script>
</head>
<body>
    <div id="example">
        <p>Original message: "{{message}}"</p>
        <p>Computed reversed: "{{reversedMessage}}"</p>
    </div>

    <div id="demo">
        <p>{{fullName}}</p>
    </div>

    <script>
        var vm = new Vue({
            el: '#example',
            data: {
                message: 'Hello'
            },
            computed: {
                // 计算属性的 getter
                reversedMessage: function () {
                    return this.message.split('').reverse().join('')
                }
            }
        })

        // 侦听属性
        /*var vm1 = new Vue({
            el: '#demo',
            data: {
                firstName: 'Foo',
                lastName: 'Bar',
                fullName: 'Foo Bar'
            },
            watch: {
                firstName: function (val) {
                    this.fullName = val + ' ' + this.lastName
                },
                lastName: function (val) {
                    this.fullName = this.firstName + ' ' + val
                }
            }
        })*/

        // 计算属性
        var vm2 = new Vue({
            el: '#demo',
            data: {
                firstName: 'Foo',
                lastName: 'Bar'
            },
            computed: {
                // 计算属性默认只有 getter ，不过在需要时你也可以提供一个 setter
                fullName: {
                    get: function () {
                        return this.firstName + ' ' + this.lastName
                    },
                    // setter
                    set: function (newValue) {
                        var names = newValue.split(' ');
                        this.firstName = names[0];
                        this.lastName = names[names.length - 1]
                    }
                }
            }
        })
    </script>
</body>
</html>